//
//  BIDRemindController.m
//  theFifth
//
//  Created by zd2011 on 13-6-7.
//
//

#import "BIDClockVC.h"
#import "BIDAClock.h"
#import <QuartzCore/QuartzCore.h>
#import "ZenKeyboard.h"
#define kStateComponent 0
#define kZipComponent 1
#define kTypeTextTag 2
#define kTimeTextTag 3
#import "BIDTypesManager.h"
#import "BIDATypes.h"
#import "BIDBillsManager.h"
#import "BIDClockManager.h"
#define kDeafultStr @"留下一笔......."
#define kListOfReminds @"list"
#define kCount @"count"
@interface BIDClockVC ()
{
   
    UIBarButtonItem *addItem;
    UIBarButtonItem *modifyItem;
    UIView *infoView;
    NSInteger whichWay;
    UISegmentedControl *segmented;
    ZenKeyboard *keyboard;
    BIDTypesManager *typeManager;
    NSInteger count;
}
@property(strong,nonatomic) NSMutableArray *listOfRemind;
@property(strong,nonatomic) NSMutableArray *typeName;
@property(strong,nonatomic) NSMutableArray *subTypeOfType;

@end

@implementation BIDClockVC
@synthesize aBill,aClock;


- (void)viewDidLoad
{
    [super viewDidLoad];
           self.title=@"一笔账单详情";
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"loa.png"]];
 
       keyboard=[[ZenKeyboard alloc] initWithFrame:CGRectMake(0, 0, 325, 205)];
    keyboard.textField=self.amountText;
    
    self.amountText.inputView=keyboard;
    infoView=[[UIView alloc] initWithFrame:CGRectMake(10, 50, 300, 380)];
    
    infoView.backgroundColor=[UIColor greenColor];
    self.listOfRemind=[[NSMutableArray alloc] init];
    
    typeManager=[BIDTypesManager shareTypesManager];
    self.typeName=[typeManager DatabaseHadTypes];
    NSInteger number=[[self.typeName objectAtIndex:0] integerValue];
    self.subTypeOfType=[typeManager listOfSubTypeInMainType:number];
      self.typePicker.hidden=YES;
    self.timePicker.hidden=YES;
    self.hiddenCancle.hidden=YES;
    self.timetext.inputView=self.timePicker;
    self.typeText.inputView=self.typePicker;
    if (aBill) {
            NSString* typename=[[BIDTypesManager shareTypesManager] selectTypeName:aBill.type_ID];
            NSString *    subType=[[BIDTypesManager shareTypesManager] selectSubTypeName:aBill.subType_ID];
        self.typeText.text=[NSString stringWithFormat:@"%@--%@",typename,subType];
        
        self.otherText.text=aBill.Cdescription;
        self.timetext.text=aBill.Ctime;
        self.amountText.text=[NSString stringWithFormat:@"%.2f",aBill.Camount];
       self.title=@"一笔账单详情";
        [self textIsEnable:NO];
    }
    if (aClock) {
        NSString* typename=[[BIDTypesManager shareTypesManager] selectTypeName:aClock.type_ID];
        NSString *    subType=[[BIDTypesManager shareTypesManager] selectSubTypeName:aClock.subType_ID];
        self.typeText.text=[NSString stringWithFormat:@"%@--%@",typename,subType];
        
        self.otherText.text=aClock.other;
        self.timetext.text=aClock.time;
        self.amountText.text=[NSString stringWithFormat:@"%.2f",aClock.amount];
        self.title=@"一个闹钟详情";
        [self textIsEnable:NO];

    }
  
}
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
    if (!aBill) {
         [self initNavView];
    }
    if (aBill) {
        [self initModifyNavView];
    }
    if (aClock) {
        self.navigationItem.rightBarButtonItem=nil;
    }
   
}
-(void)viewDidDisappear:(BOOL)animated
{
    if (segmented) {
        [segmented removeFromSuperview];
        segmented=nil;
    }

}
#pragma mark---segment
-(void)initNavViewSegment:(NSInteger)defualt
{
    segmented=[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"收入",@"支出", nil]];
    segmented.tag=100;
    segmented.tintColor=[UIColor grayColor];
    segmented.segmentedControlStyle=1;
    segmented.selectedSegmentIndex=defualt;
    segmented.frame = CGRectMake(100, 10, 100, 30);
    [segmented addTarget:self action:@selector(switchControl:) forControlEvents:UIControlEventValueChanged];
    [self.navigationController.navigationBar addSubview:segmented];
    
}
-(void)switchControl:(id)seder
{
    
    whichWay=[segmented selectedSegmentIndex];
}



-(void)initModifyNavView
{
   
    UIBarButtonItem * modifyItem1=[[UIBarButtonItem alloc] initWithTitle:@"点击修改" style:UIBarButtonItemStyleDone target:self action:@selector(isModifyText:)];
    self.navigationItem.rightBarButtonItem=modifyItem1;
}
-(void)isModifyText:(UIBarButtonItem*)iten
{
    if (![iten.title isEqualToString:@"取消修改"])
    {

        [self textIsEnable:YES];

         [self initNavViewSegment:aBill.whichWay];
                     [iten setTitle:@"取消修改"];
//           self.title=@"一笔账单详情";
              self.title = nil;
    }
    else
    {
        if (segmented)
        {
            [segmented removeFromSuperview];
            self.title=nil;
            segmented=nil;
        }

        [self modifyABill];
        
        [self textIsEnable:NO ];
        
        [iten setTitle:@"点击修改"];
        
    }

       if (![iten.title isEqualToString:@"取消修改"])
        {
           self.title=@"一笔账单详情";

              }

  
}
-(void)initNavView
{
    addItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addARemindInfo:)];
    self.navigationItem.rightBarButtonItem=addItem;
       
}

-(void)addARemindInfo:(UIButton*)send
{
   
    BIDAClock *aRemind=[[BIDAClock alloc] init];
  //  aRemind.types=self.typeText.text;
//    NSArray *arr=[self.timetext.text componentsSeparatedByString:@"分"];
  if (self.typeText.text.length!=0||self.timetext.text.length!=0) {
  
        NSArray *strArr=[self.typeText.text componentsSeparatedByString:@"--"];
    
    NSInteger type_id=[[BIDTypesManager shareTypesManager] selectTypeid:[strArr objectAtIndex:0]];
    NSInteger subType_id=[[BIDTypesManager shareTypesManager] selectSubTypeid:[strArr objectAtIndex:1]];

    aRemind.time=self.timetext.text;
    aRemind.other=self.otherText.text ;
    aRemind.type_ID=type_id;
    aRemind.subType_ID=subType_id;
    aRemind.amount=self.amountText.text.integerValue;
    [[BIDClockManager shareManager] addClock:aRemind];
    UILocalNotification *location=[[UILocalNotification alloc] init];
   // NSDate *date=[self.timePicker date];
//    NSDateFormatter *formaton=[[NSDateFormatter alloc] init];
//    [formaton setDateFormat:@"YYYY-MM-dd HH:mm"];
//   NSArray *arr11=[[self getTimePicker] componentsSeparatedByString:@"分"];
    location.timeZone=[NSTimeZone defaultTimeZone];
    NSDate *now=[self.timePicker date];
    
    location.fireDate=now;
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:kCount] integerValue]==0  ) {
        count=0;
    }
    count++;

    location.applicationIconBadgeNumber=count;
    location.hasAction=NO;
    location.alertAction=@"ddsdad";
    [[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInteger:count] forKey:kCount];
    [[NSUserDefaults standardUserDefaults] synchronize];
    location.alertBody=aRemind.other;
    location.soundName=@"clock.mp3";
    [[UIApplication sharedApplication] scheduleLocalNotification:location];
    [location release];
    
    
    
    [aRemind release];
    self.typeText.text=nil;
    self.timetext.text=nil;
    self.otherText.text=kDeafultStr;
    self.amountText.text=nil;}
    else
    {
        UIAlertView *aly=[[UIAlertView alloc] initWithTitle:@"weq" message:@"not finish" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"sure", nil];
        [aly show];
    }
    
 
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
}
#pragma mark pickerView

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == kStateComponent)
    {
        return [self.typeName count];
        
        
    }
    else
    {
        return [self.subTypeOfType count];
        
    }
}

#pragma  mark--- Picker Delegate Methods
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == kStateComponent)
    {
        NSString *str=[typeManager selectTypeName:[[self.typeName objectAtIndex:row] integerValue]];
        return str;
    }
    else
    {
        BIDATypes *type=[self.subTypeOfType objectAtIndex:row];
        NSString *str=[typeManager selectSubTypeName:type.subTypeId];
        return str;
    }
    
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component ==kStateComponent)
    {
        NSInteger number=[[self.typeName objectAtIndex:row] integerValue];
        
        self.subTypeOfType = [typeManager listOfSubTypeInMainType:number];
        [self.typePicker selectRow:0 inComponent:kZipComponent animated:YES];
        [self.typePicker reloadComponent:kZipComponent];
    }
}
#pragma mark---textFeild
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag==kTypeTextTag) {
        self.typePicker.hidden=NO;
        if (!self.timePicker.hidden) {
            self.timePicker.hidden=YES;
        }
    }
    if (textField.tag==kTimeTextTag) {
        self.timePicker.hidden=NO;
        if (!self.typePicker.hidden) {
            self.typePicker.hidden=YES;
        }
    }
    if (self.hiddenCancle) {
        self.hiddenCancle.hidden=NO;
    }
    if (textField.tag==200) {
        self.amountText.text=nil;
    }
    
    CGRect rect=self.view.frame;
    rect.origin.y-=40;
    
    [self viewMoveToDuration:0.3 andNewFrame:rect];


}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag==kTypeTextTag) {
        self.typePicker.hidden=YES;
        if (!self.timePicker.hidden) {
            self.timePicker.hidden=YES;
        }
        self.typeText.text=[self getTypePicker];
    }
    if (textField.tag==kTimeTextTag) {
        self.timePicker.hidden=YES;
        if (!self.typePicker.hidden) {
            self.typePicker.hidden=YES;
        }
        
        self.timetext.text=[self getTimePicker];
    }
    
    CGRect rect=self.view.frame;
    rect.origin.y+=40;
   [self viewMoveToDuration:0.3 andNewFrame:rect];
   // self.hiddenCancle.hidden=YES;
}
-(NSString *)getTimePicker
{
    NSDate *date=[self.timePicker date];
    NSDateFormatter *formaton=[[NSDateFormatter alloc] init];

            [formaton setDateFormat:@"YYYY-MM-dd HH:mm:ss +0800"];
//    if (aClock) {
//        [formaton setDateFormat:@"YYYY-MM-dd HH:mm:ss +0800"];
//
//    }

    NSString *srt=[formaton stringFromDate:date];
    NSArray *arr=[srt componentsSeparatedByString:@"+"];
    
    
    
    
    return [arr objectAtIndex:0] ;
}
-(NSString*)getTypePicker
{
    NSInteger stateRow =[self.typePicker selectedRowInComponent:kStateComponent];
    NSInteger zipRow = [self.typePicker selectedRowInComponent:kZipComponent];
    NSInteger  select = [[self.typeName objectAtIndex:stateRow] integerValue];
    NSString *selectType = [typeManager selectTypeName:select];
    NSInteger selectsub  =[[self.subTypeOfType objectAtIndex:zipRow] subTypeId];
    NSString *selectSubtype = [typeManager selectSubTypeName:selectsub];
    NSString *message = [[NSString alloc] initWithFormat:@"%@--%@",selectType,selectSubtype];
    return message;
}

- (void)dealloc {
    [_typePicker release];
    [_timePicker release];
    [_hiddenCancle release];
    [_typeText release];
    [_timetext release];
    [_otherText release];
    [_historyTable release];
    [_amountText release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setTypePicker:nil];
    [self setTimePicker:nil];
    [self setHiddenCancle:nil];
    [self setTypeText:nil];
    [self setTimetext:nil];
    [self setOtherText:nil];
    [self setHistoryTable:nil];
    [super viewDidUnload];
}
- (IBAction)isHiddenView:(id)sender {
    if (!self.timePicker.hidden) {
        self.timePicker.hidden=YES;
    }
    if (!self.typePicker.hidden) {
        self.typePicker.hidden=YES;
    }
    if (!self.hiddenCancle.hidden) {
        self.hiddenCancle.hidden=YES;
    }
    
    [self.timetext resignFirstResponder];
    [self.typeText resignFirstResponder];
    [self.amountText resignFirstResponder];
//    CGRect rect=self.view.frame;
//    rect.origin.y+=40;
//    self.view.frame=rect;
}

- (IBAction)backGround:(id)sender {
    [self.timetext resignFirstResponder];
    [self.typeText resignFirstResponder];
    [self.otherText resignFirstResponder];
    [self.amountText resignFirstResponder];
    if (!self.hiddenCancle.hidden) {
        self.hiddenCancle.hidden=YES;
    }
}
#pragma mark --textViewDelegate

-(void)textViewDidBeginEditing:(UITextView *)textView
{
   
    CGRect rect=self.view.frame;
    rect.origin.y-=100;
   // [textView ];
 [self viewMoveToDuration:0.5 andNewFrame:rect];

    if ([textView.text isEqualToString:kDeafultStr]) {
        textView.text=@"";
    }

}
-(void)textViewDidEndEditing:(UITextView *)textView
{
    CGRect rect=self.view.frame;
    rect.origin.y+=100;
    [self viewMoveToDuration:0.5 andNewFrame:rect];


}
#pragma mark--animation
-(void)viewMoveToDuration:(float)time andNewFrame:(CGRect)rect
{
    [UIView animateWithDuration:time animations:^{
        self.view.frame=rect;
    }];
}
#pragma mark----textEdting

-(void)textIsEnable:(BOOL)enable
{
    self.timetext.enabled=enable;
    self.typeText.enabled=enable;
    self.otherText.editable=enable;
    self.amountText.enabled=enable;
    
}
-(void)modifyABill
{
    BIDABill *abll1=[[BIDABill alloc] init];
    NSArray *arr=[self.typeText.text componentsSeparatedByString:@"--"];
    NSString *typeM=[arr objectAtIndex:0];
    NSString *subType=[arr objectAtIndex:1];
    abll1.whichWay=whichWay;
    abll1.Ctime=self.timetext.text;
    abll1.type_ID=[[BIDTypesManager shareTypesManager] selectTypeid:typeM];
    abll1.subType_ID=[[BIDTypesManager shareTypesManager] selectSubTypeid:subType];
   
    abll1.Camount=self.amountText.text.floatValue;
    abll1.Cdescription=self.otherText.text;
    [[BIDBillsManager shareBillsManager] updataThePayout:abll1 andOldPayout:aBill];
    [abll1 release];
  //  abll1.type_ID=
}
- (IBAction)swipBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
